﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.ServiceModel.DomainServices.Client;
using System.Threading;
using System.Windows;
using NetBay.Core.BusinessEntities;
using NetBay.Core.Encryption.Licensing;
using NetBay.Core.Silverlight.Extensions;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Helpers;
using Rio.Framework.Pages.Manager;
using Rio.Framework.WCFService;
using Telerik.Windows.Controls;

namespace Rio.Framework.Pages.AppCode.Context
{
    public class ApplicationContext : IApplicationService, IApplicationLifetimeAware
    {
        #region Events

        public event EventHandler ApplicationContextLoaded;

        #endregion

        /// <summary>
        /// Called by an application in order to initialize the application extension service.
        /// </summary>
        /// <param name="context">Provides information about the application state.</param>
        public void StartService(ApplicationServiceContext context)
        {
            //IApplicationService

            GlobalWebContext.RioAppSettings = context.ApplicationInitParams;

            //WCF Services Init
            ServiceManager.RioWCFEndPoint = GlobalWebContext.RioAppSettings["RioWCFServices_EndPoint"];
            ServiceManager.OpenTimeout = GlobalWebContext.RioAppSettings["WCF_OpenTimeout"];
            ServiceManager.SendTimeout = GlobalWebContext.RioAppSettings["WCF_SendTimeout"];
            ServiceManager.ReceiveTimeout = GlobalWebContext.RioAppSettings["WCF_ReceiveTimeout"];
            ServiceManager.UploadThreadPoolMaxThreads = Convert.ToInt16(GlobalWebContext.RioAppSettings["UploadThreadPoolMaxThreads"]);
            ServiceManager.UploadThreadTimeout = Convert.ToUInt32(GlobalWebContext.RioAppSettings["UploadThreadTimeout"]);
            ServiceManager.UploadThreadInterval = Convert.ToInt16(GlobalWebContext.RioAppSettings["UploadThreadInterval"]);
            ServiceManager.FileMaxLength = Convert.ToInt16(GlobalWebContext.RioAppSettings["FileMaxLength"]);
            ServiceManager.ImportOrderByDescending = Convert.ToBoolean(GlobalWebContext.RioAppSettings["Rio.Applications.Import.OrderByDescending"]);

            //License Key 
            if (GlobalWebContext.RioAppSettings["LicenseKeyDuration"] != null)
            {
                ServiceManager.LicenseKeyDuration = Convert.ToInt32(GlobalWebContext.RioAppSettings["LicenseKeyDuration"]);
            }

            //Telerik resources   
            LocalizationManager.DefaultResourceManager =
                Localisation.Manager.GetTelerikResource(
                    GlobalWebContext.RioAppSettings["Rio.Applications.Web.DefaultCulture"]);

            //Set Rio resources
            Resx.RioResourceManager = Localisation.Manager.GetRioResource(GlobalWebContext.RioAppSettings["Rio.Applications.Web.DefaultCulture"]);

            //Apply telerik Theme
            StyleManager.ApplicationTheme = Manager.TelerikThemeManager.GetTelerikTheme(GlobalWebContext.RioAppSettings["Application_Theme"]);

            //Get and set ntlm account
            string ntmlAccount = GlobalWebContext.RioAppSettings["UserAccount"];
            ntmlAccount = ntmlAccount.Substring(ntmlAccount.IndexOf(@"\") + 1,
                                                ntmlAccount.Length - ntmlAccount.IndexOf(@"\") - 1);
            GlobalWebContext.BusinessEntitiesDomainContext.SetNTLMAccount(ntmlAccount);

            //Set culture thread
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
            Thread.CurrentThread.CurrentCulture = new CultureInfo(GlobalWebContext.RioAppSettings["Rio.Applications.Web.DefaultCulture"]);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(GlobalWebContext.RioAppSettings["Rio.Applications.Web.DefaultCulture"]);

            //Get license terms
            GlobalWebContext.BusinessEntitiesDomainContext.GetLicenseTerms(delegate(InvokeOperation<LicenseTerms> retr)
            {
                GlobalWebContext.LicenseTerms = retr.Value;
                OnApplicationContextLoaded();
            }, null);
            
        }

        /// <summary>
        /// Called by an application in order to stop the application extension service.
        /// </summary>
        public void StopService()
        {
            //IApplicationService
        }

        /// <summary>
        /// Called by an application immediately before the <see cref="E:System.Windows.Application.Startup"/> event occurs.
        /// </summary>
        public void Starting()
        {
            //IApplicationLifetimeAware

            Application.Current.UnhandledException += ApplicationUnhandledException;
        }

        /// <summary>
        /// Called by an application immediately after the <see cref="E:System.Windows.Application.Startup"/> event occurs.
        /// </summary>
        public void Started()
        {
            //IApplicationLifetimeAware
        }

        /// <summary>
        /// Called by an application immediately before the <see cref="E:System.Windows.Application.Exit"/> event occurs.
        /// </summary>
        public void Exiting()
        {
            //IApplicationLifetimeAware
            Application.Current.UnhandledException -= ApplicationUnhandledException;
        }

        /// <summary>
        /// Called by an application immediately after the <see cref="E:System.Windows.Application.Exit"/> event occurs.
        /// </summary>
        public void Exited()
        {
            //IApplicationLifetimeAware
        }

        /// <summary>
        /// Applications the unhandled exception.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.ApplicationUnhandledExceptionEventArgs"/> instance containing the event data.</param>
        private void ApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            //Show error page
            ErrorPage errorPage = new ErrorPage
            {
                ErrorTitle = e.ExceptionObject.ToString(),
                ErrorMessageDetail = e.ExceptionObject.StackTrace
            };
            errorPage.Show();

            //LoggerHelper.Send(GetType().Name,
            //                  String.Format("Message : {0} - StackTrace : {1}",
            //                                e.ExceptionObject.Message,
            //                                e.ExceptionObject.StackTrace));

            // Recover from the error 
            e.Handled = true;
        }

        /// <summary>
        ///   Called when [application context loaded].
        /// </summary>
        protected void OnApplicationContextLoaded()
        {
            if (ApplicationContextLoaded != null)
            {
                ApplicationContextLoaded(this, new EventArgs());
            }
        }
    }
}